package cmd

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"reflect"
	"time"
)

var RouteList = make(map[string]reflect.Type)

func MapToJson(code int, message string, data interface{}) string {
	var ret = make(map[string]interface{})
	ret["code"] = code
	ret["message"] = message
	ret["data"] = data
	var json, _ = json.Marshal(ret)
	return string(json)
}
func ToJson(data interface{}) string {
	var json, _ = json.Marshal(data)
	return string(json)
}
func Nowtime() string {
	timeObj := time.Now()
	var str = timeObj.Format("2006/01/02 15:04:05")
	return str
}
func AddRoute(elem interface{}) {
	t := reflect.TypeOf(elem).Elem()
	RouteList[t.Name()] = t
}

func GetRoute(name string, RouteList map[string]reflect.Type) (interface{}, bool) {
	elem, ok := RouteList[name]
	if !ok {
		return nil, false
	}
	return reflect.New(elem).Elem().Interface(), true
}
func Call(m map[string]reflect.Type, name string, fn string, params interface{}) string {
	var content = ""
	obj, _ := GetRoute(name, m)
	f := reflect.ValueOf(obj)
	if f.IsValid() {
		method := f.MethodByName(fn)
		if method.IsValid() {
			in := make([]reflect.Value, 1)
			in[0] = reflect.ValueOf(params)
			s := method.Call(in)
			content = s[0].Interface().(string)

		}
	}
	return content
}
func doWork(PackageName, FuncName, Params interface{}) string {

	var content = ""
	var pkName = PackageName.(string) //获取模块名称
	var funName = FuncName.(string)   //获取调用模块方法名称
	content = Call(RouteList, pkName, funName, Params)
	return content
}
func Resquest(w http.ResponseWriter, req *http.Request) {
	params := make(map[string]interface{})
	json.NewDecoder(req.Body).Decode(&params)
	fmt.Println(Nowtime(), "Method =", req.Method)
	fmt.Println("PackageName =", params["PackageName"], "FuncName =", params["FuncName"], "Params =", params["Params"])
	var content = doWork(params["PackageName"], params["FuncName"], params["Params"])
	w.Header().Set("Content-Type", "application/json")
	if content == "" {
		content = "404"
		w.WriteHeader(404)
	} else {
		w.WriteHeader(200)
	}
	w.Write([]byte(content))
}
func StartServer(Port string) {
	fmt.Println("MVC-Go Server Port:" + Port)
	http.HandleFunc("/", Resquest)
	err := http.ListenAndServe(":"+Port, nil)
	if err != nil {
		fmt.Println("MVC-Go Server Error:", err)
	}
}
func Base64toString(data []byte) string {
	var str = base64.StdEncoding.EncodeToString(data)
	return str
}
